﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : MonoBehaviour {

    public static SoundManager Instance;
    bool isRecording;
    float recordTime=0;
    private void Awake()
    {
        Instance = this;
    }

    // Update is called once per frame
    void Update () {
        if (isRecording) {
            recordTime += Time.deltaTime;
        }
	}
    string[] mcDevices;
    AudioClip _recordClip;
    AudioSource _audioSource;
    string defaultDevice;

    public bool IsRecording
    {
        get
        {
            return isRecording;
        }

        set
        {
            isRecording = value;
        }
    }

    // Use this for initialization
    void Start()
    {
        mcDevices = Microphone.devices;
        _audioSource = GetComponent<AudioSource>();
        if (_audioSource == null)
        {
            _audioSource = gameObject.AddComponent<AudioSource>();
        }
        Debug.Log("defaultDevice  " + Microphone.devices.Length);
        defaultDevice = mcDevices[0];

    }

    public void StarRecord()
    {   
        if (!Microphone.IsRecording(defaultDevice))
        {
            recordTime = 0;
            _recordClip = Microphone.Start(defaultDevice, false, 60, 44100);
            _audioSource.clip = _recordClip;
        }
    }

    public void PlayClip(AudioClip clip) {
        if (clip==null) {
            return;
        }
        _audioSource.clip = clip;
        _audioSource.Play();
    }
    public void RecordEnd() {

        AudioClip clip = _audioSource.clip;
        if (recordTime < 60)
        {
            int sampleLength =(int) UnityEngine.Mathf.Ceil(recordTime) * _audioSource.clip.frequency;
            float[] samples = new float[sampleLength];
            _audioSource.clip.GetData(samples,0);
            clip = AudioClip.Create(DateTime.UtcNow.Ticks.ToString(), samples.Length, _audioSource.clip.channels, _audioSource.clip.frequency, false);
            clip.SetData(samples, 0);
        }
        Microphone.End(defaultDevice);
        UIManager.Instance.CreatTalkElement(false, clip);
        
    }
}